package com.woniu.his.bms.app.exception;

import com.woniu.his.exception.HisException;
import com.woniu.his.result.CommonResultCode;
import com.woniu.his.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //@ControllerAdvice
@Slf4j
public class GlobalException {

        @ExceptionHandler(Exception.class) //系统异常
        public Result handleException(Exception e) {
            log.error("执行出错", e);
            if (e instanceof DuplicateKeyException) {
                return Result.getInstance().setCode(501).setMsg( "数据库失败");
            }

//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();

            return Result.getInstance(CommonResultCode.GENERAL_FAIL);
        }

        @ExceptionHandler(HisException.class) //业务异常
        public Result handleAppException(HisException e) {

            log.warn("出现业务异常:" + e.getMessage(), e);
//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();

            return Result.getInstance().setCode(e.getCode()).setMsg( e.getMessage());
        }

        @ExceptionHandler(MethodArgumentNotValidException.class)
        public Result handleBindException(MethodArgumentNotValidException e) {

            StringBuilder errorMsgBuilder = new StringBuilder();
            List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                errorMsgBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";");
            }
//            GlobalTransactionContext.reload(RootContext.getXID()).rollback();

            return Result.getInstance(CommonResultCode.INVALID_PARAM);
        }


}
